// 获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    modelid: '',
    wW: 200,
    wH: 200,
    model: {
      CanDo: true,
      PlaceId: 0,
      CategoryId: 0,
      StartOn: '',
      EndOn: '',
      LastUpdateOn: '',
      Inspections: [], // 报修记录
      Maintenances: [], // 巡检记录
    },
    hasCamera: false,
    showVideo: false,
    videoUrl: '',
    showPop: false, // 是否显示蒙版(补充说明)
    maxFiles: 3,
    files: [],
    remark: '无异常',
    allPlaces: [],
    places: [],
    categories: [],
    searchPlaceValue: '',
    showPlaceAction: false,
    showPlace: false,
    categoryActiveIndex: 0,
    categoryActiveId: null,
    showCategory: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let _this = this;
    let _id = options.id || '';
    const {
      windowHeight,
      windowWidth
    } = wx.getWindowInfo();
    _this.loadDetail(_id);
    _this.setData({
      modelid: _id,
      wW: windowWidth,
      wH: windowHeight
    })
    _this.videoContext = wx.createVideoContext('myVideo'); //视频播放
  },
  tapImg(e) {
    let _this = this;
    let _idx = e.currentTarget.dataset.idx
    wx.previewImage({
      urls: _this.data.model.Pictures,
      current: _this.data.model.Pictures[_idx]
    });
  },
  tapImgMin(e) {
    let _this = this;
    const {
      idx,
      pics
    } = e.currentTarget.dataset;
    wx.previewImage({
      urls: pics,
      current: pics[idx]
    });
  },
  tapDelImg(e) {
    let _this = this;
    let _idx = e.currentTarget.dataset.idx
    let _files = _this.data.files;
    _files.splice(_idx, 1);
    _this.setData({
      files: _files
    });
  },
  addImage(e) {
    let _this = this;
    wx.chooseMedia({
      mediaType: ['image'],
      sourceType: ['camera'],
      sizeType: ['compressed'],
      success: function (res) {
        let _files = _this.data.files;
        if (res.tempFiles.length + _files.length > _this.data.maxFiles) {
          wx.showToast({
            icon: 'none',
            title: `最多允许上传${_this.data.maxFiles}张图片`
          });
          return;
        }
        let startIdx = _files.length;
        for (let i = 0; i < res.tempFiles.length; i++) {
          _files.push({
            img: res.tempFiles[i].tempFilePath,
            percent: 0,
            id: 0,
            unique: startIdx + i
          });
        }
        _this.setData({
          files: _files
        }, function () {
          for (let j = 0; j < res.tempFiles.length; j++) {
            _this.uploadImg(res.tempFiles[j].tempFilePath, startIdx + j);
          }
        });
      }
    });
  },
  uploadImg(file, idx) {
    let _this = this;
    var task = wx.uploadFile({
      url: `${app.apiRoot}Picture/AsyncUpload`,
      filePath: file,
      name: 'qqfile',
      success(resp) {
        var data = JSON.parse(resp.data) //返回的是[字符串]，需要自己转为JSON格式
        let _files = _this.data.files;
        _files[idx].id = data.pictureId;
        _this.setData({
          files: _files
        });
      },
      fail(resp) {
        console.log('fail', resp);
      }
    });

    task.onProgressUpdate((res) => {
      let _files = _this.data.files;
      _files[idx].percent = res.progress;
      _this.setData({
        files: _files
      });
    });
  },
  loadDetail(id) {
    let _this = this;
    app.ajax({
      url: 'InspectionPlan/View',
      data: {
        planId: id
      },
      success(resp) {
        if (resp.model) {
          const _allPlaces = resp.model.AvailablePlaces || [];
          const _places = _allPlaces;
          const _categories = (resp.model.AvailableCategories.filter(m => m.PId == 0) || []).map(s => {
            var children = (resp.model.AvailableCategories.filter(m => m.PId == s.Id) || []).map(d => {
              return {
                id: d.Id,
                text: d.Text
              };
            });
            children.unshift({
              id: s.Id,
              text: s.Text,
            });
            return {
              id: s.Id,
              text: s.Text,
              children
            };
          });
          _this.setData({
            model: resp.model,
            places: _places,
            categories: _categories,
            allPlaces: _allPlaces,
          });
        }
      }
    });
  },
  onShareAppMessage() {
    return {
      title: app.app.title,
      desc: app.app.desc,
      path: '/pages/inspection/detail?id=' + this.data.modelid
    };
  },
  showPop() {
    let _this = this;
    _this.setData({
      showPop: true
    });
  },
  addMaintenance() {
    let _this = this;
    wx.redirectTo({
      url: "/pages/maintenance/edit?planId=" + _this.data.modelid
    });
  },
  onClose() {
    let _this = this;
    _this.setData({
      showPop: false,
    });
  },

  onChange(e) {
    const {
      detail
    } = e;
    this.setData({
      remark: detail
    });
  },

  doSave(e) {
    let _this = this;
    let status = e.currentTarget.dataset.status;
    const {
      modelid,
      remark,
      files,
      model
    } = _this.data;
    if (!remark) {
      app.showNotify('请输入巡检说明');
      return;
    }
    if (remark != '无异常' && files.length === 0) {
      app.showNotify('请上传现场图片');
      return;
    }
    if (status === '1') {
      if (remark != '无异常') {
        app.showNotify('有异常时，请点击报修');
        return;
      }
    }
    if (status === '2') {
      if (remark === '无异常') {
        app.showNotify('无异常时，请点击提交');
        return;
      }
      if (model.PlaceId == 0) {
        app.showNotify('请选择巡检点');
        return;
      }
      if (files.length === 0) {
        app.showNotify('请上传现场图片');
        return;
      }
    }
    let _imgs = '';
    let _picDone = true;
    for (let i = 0; i < files.length; i++) {
      if (files[i].id <= 0) {
        _picDone = false;
        break;
      } else {
        _imgs += files[i].id + ',';
      }
    }
    if (!_picDone) {
      app.showNotify('请等待图片上传完成');
      return;
    }
    app.ajax({
      url: 'Inspection/Add',
      data: {
        planId: modelid,
        comment: remark,
        SelectedPictureIds: _imgs,
        bx: status === '2',
        placeId: model.PlaceId,
        placeName: model.PlaceName,
        categoryId: model.CategoryId,
        categoryName: model.CategoryName,
      },
      success: function (resp) {
        if (!resp.result) {
          app.showNotify(resp.msg);
        } else {
          wx.showToast({
            title: '提交成功',
            complete() {
              _this.setData({
                showPop: false,
                files: [],
                remark: '无异常',
              });
              _this.loadDetail(_this.data.modelid);
            }
          });
        }
      },
    });
  },
  startCamera() {
    const {
      modelid
    } = this.data;
    wx.navigateTo({
      url: '/pages/camera/index?id=' + modelid
    });
  },
  playCamera() {
    const _this = this;
    _this.setData({
      videoUrl: _this.data.model.Videos[0],
      showVideo: true
    });
    _this.videoContext.play();
  },
  playPersonCamera(e) {
    let _this = this;
    const {
      videos
    } = e.currentTarget.dataset;
    _this.setData({
      videoUrl: videos[0],
      showVideo: true
    });
    _this.videoContext.play();
  },
  //移除已有录像
  removeCamera() {
    let _this = this;
    _this.setData({
      hasCamera: false
    });
  },
  hideVideo() {
    this.videoContext.stop();
    this.setData({
      showVideo: false
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 显示设备分类选择框
  showCategory(e) {
    this.setData({
      showCategory: true
    });
  },
  closeCategory() {
    this.setData({
      showCategory: false
    });
  },
  closePlace() {
    this.setData({
      showPlace: false
    });
  },
  onCategoryClickNav({
    detail = {}
  }) {
    this.setData({
      categoryActiveIndex: detail.index || 0
    });
  },
  onCategoryClickItem({
    detail = {}
  }) {
    const {
      model,
      allPlaces,
    } = this.data;
    const categoryActiveId = detail.id;
    model.CategoryId = categoryActiveId;
    model.CategoryName = detail.text;

    // const _places = (allPlaces || []).filter(m => m.PId === categoryActiveId);
    this.setData({
      categoryActiveId,
      model,
      showCategory: false,
      // places: _places,
    });
  },
  // 显示巡检点选择框
  showPlace(e) {
    this.setData({
      showPlace: true,
    });
  },
  onPlaceSearch({
    detail
  }) {
    const {
      allPlaces
    } = this.data;
    const _places = (allPlaces || []).filter(m => m.Text.indexOf(detail) != -1);
    this.setData({
      searchPlaceValue: detail,
      places: _places,
    });
  },
  onPlaceFocus() {
    this.setData({
      showPlaceAction: true
    });
  },
  onPlaceCancel() {
    const {
      allPlaces
    } = this.data;
    this.setData({
      showPlaceAction: false,
      searchPlaceValue: '',
      places: allPlaces,
    });
  },
  selectPlace(e) {
    const {
      target: {
        id
      }
    } = e;
    let _this = this;
    const {
      model,
      allPlaces
    } = _this.data;
    const place = allPlaces.filter(m => m.Id == id * 1)[0];
    if (place) {
      model.PlaceId = place.Id;
      model.PlaceName = place.Text;
      _this.setData({
        showPlace: false,
        model
      });
    }
  },
})